import axios from 'axios';
import router from '@/router';

// import api from '@/api';
const instance = new axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'client_id': 'webApp',
    'client_secret': 'webApp'
  },
  timeout: 120000 // 超时2分钟
});

instance.interceptors.request.use(
  (config) => {
    const token = store.state.user.accesstoken || '';
    // todo 登录与不登录的判断。
    if (config.isJson) {
      config.headers['Content-Type'] = 'application/json';
    } else {
      config['transformRequest'] = function (data) {
        let str = '';
        for (const key in data) {
          str += `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}&`;
        }
        return str.substring(0, str.length - 1);
      };
    }

    if (!config.notLogin) {
      // 部分不需要登录就能访问的接口需要在config添加'notLogin'键
      // { notLogin: true }
      // debugger;
      if (config.url !== '/api-auth/oauth/wechat/isLogin') {
        return new Promise(function (resolve, reject) {
          if (token) {
            if (config.isAuth) {
              config.headers.Authorization = `Bearer ${token}`;
            } else {
              config.headers.Authorization = `bearer ${token}`;
            }
            instance
              .post('/api-auth/oauth/wechat/isLogin', { accesToken: token })
              .then((res) => {
                if (res.data.payload) {
                  resolve(config);
                } else {
                  notLoginFunc();
                }
              });
          } else {
            // token 为空时不进行接口校验
            notLoginFunc();
          }

          function notLoginFunc() {
            store.dispatch('removeUser', true);
            if (config.loginway === 'ecs') {
              Dialog.confirm({
                title: '请先登录'
              }).then(() => {
                // on close
                allLoginMethod.ecsLoginFunc();
              });
            } else {
              if (router.currentRoute.value.meta.loginMode === 'ecs') {
                showEcsLogin();
              } else {
                showLoginBox();
              }
            }
            // catch块中code = -1时，表示登录校验失败
            reject({ code: -1 });
          }
        });
      }
    }

    return config;
    // return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (res) => {
    const { data, code, msg = '未知错误' } = res.data;

    if (code === 0 || code === 200) {
      /*请求成功 + 自定义错误码（200~300）在请求成功处捕捉错误 ,旧版接口的100是成功*/
      return res.data;
    } else {
      if (data >= 200 && data < 300) {
        return res.data;
      } else {
        Toast(msg);
      }
    }
    return Promise.reject(msg);
  },
  (err) => {
    const { config, response, code } = err;
    // code=-1为前端自己定义的错误码
    if (code === -1) {
      Toast.clear();
      return Promise.reject(err);
    }
    if (!config.notToastErr) {
      if (response) {
        if (response.status === 401) {
          if (router.currentRoute.value.meta === 'ecs') {
            showEcsLogin();
          } else {
            showLoginBox();
          }
          return Promise.reject(err);
        } else if (response.status === 500) {
          Toast(response.data.msg);
          return Promise.reject(err);
        }
      }
      Toast('网络错误');
    }
    return Promise.reject(err);
  }
);

export default instance;
